package com.xysq.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.viewpagerindicator.UnderlinePageIndicator;
import com.xysq.adapter.ImagePagerAdapter;
import com.xysq.fragment.ImageFragment;
import com.xysq.lemon.R;
import com.xysq.util.CollectionUtil;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 查看大图 Activity
 */
public class ImagesActivity extends BaseActivity {

    public static final String PARAM_IMAGE_URLS = "param_image_urls";
    public static final String PARAM_CURRENT_POSITION = "param_current_position";

    // @formatter:off
    @InjectView(R.id.pager)
    ViewPager mPager;
    @InjectView(R.id.txt_indicator)
    TextView indicatorTxt;
    @InjectView(R.id.txt_save)
    TextView saveTxt;
    int currentPosition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_images);
        ButterKnife.inject(this);

        Intent paramIntent = getIntent();
        final List<String> urls = paramIntent.getStringArrayListExtra(PARAM_IMAGE_URLS);
        currentPosition = paramIntent.getIntExtra(PARAM_CURRENT_POSITION, 0);
        if (CollectionUtil.isNullOrEmpty(urls)) {
            ToastUtil.showShort(this, R.string.txt_error_empty_image_url);
            finish();
            return;
        }

        final ImagePagerAdapter pagerAdapter = new ImagePagerAdapter(getSupportFragmentManager());
        pagerAdapter.appendList(urls);
        mPager.setAdapter(pagerAdapter);
        mPager.setCurrentItem(currentPosition);
        indicatorTxt.setText((currentPosition + 1) + "/" + pagerAdapter.getCount());
        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                indicatorTxt.setText((currentPosition + 1) + "/" + pagerAdapter.getCount());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        saveTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread() {
                    @Override
                    public void run() {
                        Bitmap bitmap = returnBitmap(PropertiesUtil.getImageServer() + urls.get(currentPosition));
                        saveImage(bitmap);
                    }
                }.start();
                ToastUtil.showShort(ImagesActivity.this, "图片已经保存到手机");
            }
        });
    }

    public void saveImage(Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "Xiaoyou");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}
